package net.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.kernel.KVisiteur;
import net.ko.framework.Ko;
import net.ko.http.objects.KRequest;
import net.ko.kobject.KObject;
import net.ko.mapping.IMappingControl;

public class LoginControl implements IMappingControl {
	
	private String erreur="";
	
	@Override
	public boolean isValid(HttpServletRequest request,
			HttpServletResponse response) {
		boolean result = false;
		if (KRequest.keyExists("login", request)) {
			String login = KRequest.GETPOST("login", request);
			String mdp = KRequest.GETPOST("mdp", request);
			System.out.println("mot de passe : " + mdp);
			try {
				KVisiteur vi = (KVisiteur) KObject.kloadOne(KVisiteur.class,
						Ko.kdatabase(), "login='" + login + "'");
				if (mdp.equals(vi.getMdp())) {
					request.setAttribute("activeVisiteur", vi);
					request.getSession().setAttribute("activeVisiteur", vi);
					request.getSession().setAttribute("statut",vi.getStatut());
					request.getSession().setAttribute("id", vi.getId());
					result = true;
				} else {
					request.setAttribute("activeVisiteur", null);
					erreur = "Utilisateur ou mot de passe incorrect";
				}
			} catch (InstantiationException | IllegalAccessException
					| ClassNotFoundException | SQLException e) {
				erreur = "Internal server error";
				e.printStackTrace();
			}

		} 
			
		
		return result;
	}

	@Override
	public void onInvalidControl(HttpServletRequest request,
			HttpServletResponse response) {
		 try {
			 request.setAttribute("erreur", erreur);
			KRequest.forward("/login.do", request, response,"erreur="+erreur);
		} catch (ServletException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	public boolean beforeProcessAction(HttpServletRequest request,
			HttpServletResponse response) {
		// TODO Auto-generated method stub
		return true;
	}

}
